﻿using System.Reflection;
using System.Text;
using rpc_service.cache;
using rpc_service.config;
using rpc_service.core.poll;
using rpc_service.core.registry;

namespace rpc_service.core.support.assembly.roslyn.handle;

public class RoslynUrlHandle
{
    private readonly Type _pollType;
    private readonly Type _registryType;
    
    public RoslynUrlHandle(Type pollType, Type registryType)
    {
        _pollType = pollType;
        _registryType = registryType;
    }
    
    public void GetUrl(StringBuilder stringBuilder, Type targetType, MethodInfo targetMethod)
    {
        string prefixUrl = targetType.GetCustomAttribute<RPCClass>()!.Path;
        Type stringType = "string".GetTypeByStr();
        
        stringBuilder.AppendLine($@"{stringType} url = ""{prefixUrl}"";");

        if (!prefixUrl.StartsWith("http://") &&
            !prefixUrl.StartsWith("https://"))
        {
            // 通过轮询的方式加载 注册中心的地址
            Type pollType = "Poll".GetTypeByStr();
            Type registryType = "Registry".GetTypeByStr();
            Type LoadConfigType = "LoadConfig".GetTypeByStr();
            stringBuilder.AppendLine($@"{registryType} registry = {_registryType}.GetInstance({LoadConfigType}.Load());");
            stringBuilder.AppendLine($@"{pollType} poll = new {_pollType}(registry.GetServices());");
            stringBuilder.AppendLine($@"url = ""http://"" + poll.GetUrl(""{prefixUrl}"") + ""/"";");
        } 
        else if ((prefixUrl.StartsWith("http://") ||
                 prefixUrl.StartsWith("https://")) &&
                 !prefixUrl.EndsWith("/"))
        {
            stringBuilder.AppendLine($@"url = ""{prefixUrl}"" + ""/"";");
        }
        
        stringBuilder.AppendLine($@"url = url + ""{targetMethod.GetCustomAttribute<RPCMethod>()!.Path}"";");
    }
}